from django.utils.decorators import method_decorator
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
import listen_book.plugin.sendEmail as Send
from django.views import View
from listen_book import models
from book_manage.models import AudioBook
import json
import os
import datetime
from django.contrib import auth
from django.core import serializers
from django.db.models import Q
from django.db.models import Avg, Max, Min, Count, Sum

# 对应数据库
# from django.contrib.auth.models import User
import random

# Client Enter
def home_page(request):
    return render(request, 'home.html')

# Create your views here.
# 注册
class Register(View):

    # 获取验证码
    def get(self, request):
        email = request.GET.get('email')
        global CODE
        CODE = Send.getCode()
        print(CODE)
        # Send.send(email, CODE)
        return JsonResponse({'msg': '发送成功', 'status': 200})

    # 注册
    def post(self, request, *args, **kwargs):
        # 获取注册信息
        register_json_data = request.body
        # json转为字典
        register_data = json.loads(register_json_data)

        data = {'msg': 'msg'}
        # 验证功能
        print(register_data)
        global CODE
        print(CODE)
        if str(CODE) == register_data['code']:
            # 注册
            try:
                models.UserInfo.objects.create_user(username=register_data['username'],
                                                    email=register_data['email'],
                                                    password=register_data['passward'])
                data['msg'] = '注册成功'

            except:
                data['msg'] = '用户名重复'

            return JsonResponse(data)

        else:
            data['msg'] = '验证码不正确'
            return JsonResponse(data)


# 登录
class Login(View):
    def post(self, request):
        resp = {'msg': '登录错误'}
        login_msg = request.body
        login_dir = json.loads(login_msg)
        username, password = login_dir['username'], login_dir['passward']

        # 用户验证
        user = auth.authenticate(username=username, password=password)
        print(user)
        if user is not None:
            # 登录
            auth.login(request, user)
            resp['user'] = str(request.user)
            resp['user'] = str(user)
            print(request.user.username)
            resp['msg'] = '登陆成功'
            return JsonResponse(resp)
        else:
            resp['msg'] = '用户名或密码错误'

        return JsonResponse(resp)


# 登出
class Logout(View):
    def get(self, req):
        auth.logout(req)
        data = {'msg': 'success'}

        return JsonResponse(data, safe=False)


# 获取用户信息
class GetUserInfo(View):
    def get(self, req):
        user = req.GET.get('username')
        data = {}
        try:
            userinfo = models.UserInfo.objects.filter(username=user)
            user_info_json = serializers.serialize('json', userinfo)
            # print(user_info_json)
            data = user_info_json
        except:
            data = {'data': '服务器错误'}
            print('false')

        return JsonResponse(data, safe=False)

    def post(self, req):

        return JsonResponse({'data': 'false'})


# 修改用户信息
class ModifyUserINfo(View):
    def post(self, request):
        data = {'state': 'SUCCESS'}

        info = request.body
        info_dir = json.loads(info)
        print(info_dir['type'])

        # 邮箱用户名不可修改
        if info_dir['type'] == 'email' or info_dir['type'] == 'username':
            data['data'] = '不可修改'
            return JsonResponse(data)
        if info_dir['type'] != 'tx':
            result = models.UserInfo.objects.filter(
                username=info_dir['username']).update(**{info_dir['type']: info_dir[info_dir['type']]})
            print(result)
        # 返回最新信息

        query = models.UserInfo.objects.filter(
            username=info_dir['username'])
        user_info_json = serializers.serialize('json', query)
        print(user_info_json)
        data['data'] = user_info_json

        return JsonResponse(data)


# 上传头像
class Upload(View):
    def post(self, request):
        data = request.POST.get('user')
        files = request.FILES.getlist('file')[0]

        if(not files):
            return HttpResponse('No File')

        # 上传到static中
        dist = open(os.path.join('static/head_image', files.name), 'wb+')
        for chunk in files.chunks():
            dist.write(chunk)
        dist.close()

        # 数据库更新路径
        img_path = '/static/head_image/' + files.name
        result = models.UserInfo.objects.filter(
            username=data).update(headImage=img_path)
        print(result)

        return HttpResponse('true')


# 充值
class ChargeCoin(View):
    def post(self, request):
        data = json.loads(request.body)
        res = {}
        print(data['user'], data['charge'], data['vip'])
        # 获取原有信息
        user = models.UserInfo.objects.get(username=data['user'])
        charge = int(user.coin) + int(data['charge'])
        nowVip = user.vip
        now = datetime.date.today()
        if nowVip == None:
            vip = (
                now + datetime.timedelta(days=data['vip'])).strftime("%Y-%m-%d")
        elif now > nowVip:
            vip = (
                now + datetime.timedelta(days=data['vip'])).strftime("%Y-%m-%d")
        else:
            vip = (
                nowVip + datetime.timedelta(days=data['vip'])).strftime("%Y-%m-%d")

        print(charge, nowVip, vip)

        try:

            # 充值
            models.UserInfo.objects.filter(
                username=data['user']).update(coin=charge, vip=vip)
            # 返回最新信息
            query = models.UserInfo.objects.filter(
                username=data['user'])
            user_info_json = serializers.serialize('json', query)
            res['state'] = 'success'
            res['data'] = user_info_json
            print(user_info_json)

        except:
            print('error')
            res['state'] = 'False'
        return JsonResponse(res)


# 签到
class Sign(View):
    def post(self, request):
        data = {}
        return JsonResponse(data)

    # 补签置换书券
    def get(self, request):
        username = request.GET.get('username')
        types = request.GET.get('type')
        try:
            user = models.UserInfo.objects.get(username=username)
        except:
            return JsonResponse({'state': 'false'})
        if types == 0:

            models.UserInfo.objects.filter(username=username).update(
                coin=(user.coin-10), coupon=(user.coupon + 20))
        else:
            models.UserInfo.objects.filter(username=username).update(
                coupon=(user.coupon + 20))

        print(username, types)
        return JsonResponse({'state': 'true'})


# 收藏
class Collect(View):
    def post(self, request):
        param = json.loads(request.body)
        data = {}
        # try:
        user = models.UserInfo.objects.filter(username=param['user'])[0]
        book = models.AudioBook.objects.filter(
            bookId=param['bookId']).first()

        if param['state'] == 0:  # 收藏
            collect = models.Collect(date=datetime.date.today())
            collect.bookId = book
            collect.user = user
            collect.save()
            data['state'] = 'collect success'

        elif param['state'] == 1:  # 取消收藏
            models.Collect.objects.filter(
                user=param['user'], bookId=param['bookId']).delete()
            data['state'] = 'delete success'

        elif param['state'] == 2:  # 是否收藏
            state = models.Collect.objects.filter(
                user=param['user'], bookId=param['bookId']).exists()
            print(state)
            data['state'] = state

        elif param['state'] == 3:  # 获取收藏列表
            collect_list = models.Collect.objects.filter(
                user=param['user']).order_by("date")
            res = []
            for i in collect_list:
                res.append(i.bookId)

            print(res)
            data['state'] = serializers.serialize('json', res)
        # except:
        #     data['state'] = 'error'

        return JsonResponse(data)


# 书架
class BookShelf(View):
    def post(self, request):
        param = json.loads(request.body)
        data = {}
        # try:
        user = models.UserInfo.objects.filter(username=param['user']).first()
        book = models.AudioBook.objects.filter(
            bookId=param['bookId']).first()

        if param['state'] == 0:  # 加入
            collect = models.Shelf(date=datetime.date.today())
            collect.bookId = book
            collect.user = user
            collect.save()
            data['state'] = 'collect success'

        elif param['state'] == 1:  # 取消
            models.Shelf.objects.filter(
                user=param['user'], bookId=param['bookId']).delete()
            data['state'] = 'delete success'

        elif param['state'] == 2:  # 是加入
            state = models.Shelf.objects.filter(
                user=param['user'], bookId=param['bookId']).exists()
            print(state)
            data['state'] = state

        elif param['state'] == 3:  # 获取列表
            collect_list = models.Shelf.objects.filter(
                user=param['user']).order_by("date")
            res = []
            for i in collect_list:
                res.append(i.bookId)

            print(res)
            data['state'] = serializers.serialize('json', res)
        # except:
        #     data['state'] = 'error'

        return JsonResponse(data)


# 评论 UserComment
class UserComment(View):
    def post(self, request):
        param = json.loads(request.body)
        data = {}
        # 获取评论
        if(param['state'] == 0):

            comment = models.Comment.objects.filter(bookId=param['bookId']).values_list(
                "date", "comment", "user__username", "user__headImage", "id")
            score = models.Comment.objects.filter(
                bookId=param['bookId']).aggregate(c=Avg('score'))
            print(comment)
            data = {
                'comment': list(comment),
                'score': score
            }
        # 用户评论
        elif(param['state'] == 1):
            user = models.UserInfo.objects.filter(
                username=param['user']).first()
            book = models.AudioBook.objects.filter(
                bookId=param['bookId']).first()
            comment = models.Comment(date=datetime.date.today(
            ), score=param['rate'], comment=param['comment'])
            comment.bookId = book
            comment.user = user
            comment.save()
            print(comment)
            data = {
                'state': '评论成功'
            }
        # 删除评论
        elif(param['state'] == 2):
            models.Comment.objects.filter(id=param['id']).delete()
            data = {
                'state': '删除评论'
            }
        # 获取用户所有评论
        elif param['state'] == 3:
            print(param['user'])
            comment = models.Comment.objects.filter(user=param['user']).values_list(
                "date", "comment", "bookId_id__bookName", "bookId_id__img", "id")
            data = {
                'comment': list(comment),
            }

        return JsonResponse(data)


# 购买章节
class BuyBook(View):
    def get(self, request):
        user = request.GET.get('user')
        print(user)
        lists = models.BuyChapter.objects.values_list(
            'chapterId').filter(user=user)
        print(lists)
        data = {'list': list(lists)}
        return JsonResponse(data)

    def post(self, request):
        # user chapterId
        param = json.loads(request.body)
        print(param)
        data = {}
        try:
            user = models.UserInfo.objects.get(username=param['user'])
            print(user.coupon)
            if user.coupon >= 20:
                models.UserInfo.objects.filter(
                    username=param['user']).update(coupon=user.coupon-20)
                buy = models.BuyChapter(
                    user=user, chapterId=param['chapterId'])
                buy.save()
                data['msg'] = '书券购买成功'
            elif user.coin >= 20:
                models.UserInfo.objects.filter(
                    username=param['user']).update(coin=user.coin-20)
                buy = models.BuyChapter(
                    user=user, chapterId=param['chapterId'])
                buy.save()

                data['msg'] = '书币购买成功'
            else:
                data['msg'] = '余额不足'

        except:
            data['msg'] = '请先登录'

        return JsonResponse(data)
